//
//  AVCapturePreviewView.m
//  CaptureDemo
//
//  Created by 苏沫离 on 2018/9/11.
//  Copyright © 2018年 苏沫离. All rights reserved.
//

#import "AVCapturePreviewView.h"
#import <AVFoundation/AVFoundation.h>


UIImage * const resourceImage(NSString *imageName)
{
    return [UIImage imageNamed:[@"RecordResource.bundle" stringByAppendingPathComponent:imageName]];
}

@interface AVCapturePreviewView ()

@property (nonatomic ,strong) AVCaptureDevice *device;

//聚焦
@property(nonatomic ,strong) UIView *focusView;

//缩放
@property (nonatomic ,strong) UISlider *slider;
@property (nonatomic ,assign) CGFloat currentZoomFactor;
@property (nonatomic ,assign) CGFloat minZoomFactor;
@property (nonatomic ,assign) CGFloat maxZoomFactor;

@end


@implementation AVCapturePreviewView

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    
    if (self)
    {
        self.backgroundColor = [UIColor whiteColor];
        [self addSubview:self.focusView];
        [self addSubview:self.slider];

        //添加一个聚焦手势
        UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(focusAndExposeTapGestureRecognizerClick:)];
        [self addGestureRecognizer:tapGestureRecognizer];
        
        //缩放
        UIPinchGestureRecognizer *pinchGestureRecognizer = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(zoomChangePinchGestureRecognizerClick:)];
        [self addGestureRecognizer:pinchGestureRecognizer];
        
    }
    return self;
}

#pragma mark - response click

//聚焦
- (void)focusAndExposeTapGestureRecognizerClick:(UITapGestureRecognizer *)gestureRecognizer
{
    CGPoint touchPoint = [gestureRecognizer locationInView:gestureRecognizer.view];//触摸点
    //触摸屏幕的坐标点需要转换成0-1，设置聚焦点
    CGPoint focusPoint = [self.videoPreviewLayer captureDevicePointOfInterestForPoint:touchPoint];
    if (self.delegate && [self.delegate respondsToSelector:@selector(focusAndExposeTapLocation:)]) {
        [self.delegate focusAndExposeTapLocation:focusPoint];
        
        _focusView.center = touchPoint;
        _focusView.hidden = NO;

        __weak typeof(self) weakSelf = self;
        [UIView animateWithDuration:0.3 animations:^{
            __strong typeof(weakSelf) strongSelf = weakSelf;
             strongSelf.focusView.transform = CGAffineTransformMakeScale(1.25, 1.25);
         }completion:^(BOOL finished)
         {
             [UIView animateWithDuration:0.5 animations:^{
                  weakSelf.focusView.transform = CGAffineTransformIdentity;
              }completion:^(BOOL finished){
                  weakSelf.focusView.hidden = YES;
              }];
         }];
    }
}

- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer
{
    if ([gestureRecognizer isKindOfClass:[UIPinchGestureRecognizer class]]){
        self.slider.minimumValue = self.minZoomFactor;
        self.slider.maximumValue = self.maxZoomFactor;
        self.currentZoomFactor = self.device.videoZoomFactor;
    }
    return YES;
}

//缩放手势
- (void)zoomChangePinchGestureRecognizerClick:(UIPinchGestureRecognizer *)pinchGestureRecognizer
{
    if (pinchGestureRecognizer.state == UIGestureRecognizerStateBegan ||
        pinchGestureRecognizer.state == UIGestureRecognizerStateChanged)
    {
        CGFloat currentZoomFactor = self.currentZoomFactor * pinchGestureRecognizer.scale;
        self.slider.hidden = NO;
        
        if (currentZoomFactor < self.maxZoomFactor &&
            currentZoomFactor > self.minZoomFactor){
            
            NSError *error = nil;
            if ([self.device lockForConfiguration:&error] ) {
                self.device.videoZoomFactor = currentZoomFactor;
                self.slider.value = self.device.videoZoomFactor;
                [self.device unlockForConfiguration];
            }
            else {
                NSLog( @"Could not lock device for configuration: %@", error );
            }
        }
    }
    else
    {
        self.slider.hidden = YES;
    }
}

- (void)sliderValueChangeClick:(UISlider *)sender
{
    self.slider.hidden = NO;
    
    if (sender.value < self.maxZoomFactor &&
        sender.value > self.minZoomFactor){
        
        NSError *error = nil;
        if ([self.device lockForConfiguration:&error] ) {
            self.device.videoZoomFactor = sender.value;
            [self.device unlockForConfiguration];
        }
        else {
            NSLog( @"Could not lock device for configuration: %@", error );
        }
    }
}

#pragma mark - setter and getter

+ (Class)layerClass
{
    return [AVCaptureVideoPreviewLayer class];
}

- (AVCaptureVideoPreviewLayer *)videoPreviewLayer
{
    return (AVCaptureVideoPreviewLayer *)self.layer;
}

- (AVCaptureSession *)session
{
    return self.videoPreviewLayer.session;
}

- (void)setSession:(AVCaptureSession *)session
{
    self.videoPreviewLayer.session = session;
}

- (AVCaptureDevice *)device
{
    if ([self.session.inputs.firstObject isKindOfClass:[AVCaptureDeviceInput class]]){
        return ((AVCaptureDeviceInput*)(self.session.inputs.firstObject)).device;
    }
    return nil;
}

- (UIView *)focusView
{
    if (_focusView == nil)
    {
        _focusView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 80, 80)];
        _focusView.layer.borderWidth = 1.0;
        _focusView.layer.borderColor =[UIColor greenColor].CGColor;
        _focusView.backgroundColor = [UIColor clearColor];
        _focusView.hidden = YES;
    }
    return _focusView;
}

- (UISlider *)slider
{
    if (_slider == nil) {
        _slider = [[UISlider alloc] initWithFrame:CGRectMake(50, 0, CGRectGetWidth(UIScreen.mainScreen.bounds), 38)];
        _slider.center = self.center;
        [_slider addTarget:self action:@selector(sliderValueChangeClick:) forControlEvents:UIControlEventValueChanged];
        _slider.hidden = YES;
    }
    return _slider;
}

//最小缩放值
- (CGFloat)minZoomFactor
{
    CGFloat minZoomFactor = 1.0;
    if (@available(iOS 11.0, *)) {
        minZoomFactor = self.device.minAvailableVideoZoomFactor;
    }
    return minZoomFactor;
}

//最大缩放值
- (CGFloat)maxZoomFactor
{
    CGFloat maxZoomFactor = self.device.activeFormat.videoMaxZoomFactor;
    if (@available(iOS 11.0, *)) {
        maxZoomFactor = self.device.maxAvailableVideoZoomFactor;
    }
    
    if (maxZoomFactor > 6.0) {
        maxZoomFactor = 6.0;
    }
    return maxZoomFactor;
}

- (void)setCurrentZoomFactor:(CGFloat)currentZoomFactor
{
    _currentZoomFactor = currentZoomFactor;
    self.slider.value = currentZoomFactor;
}

@end
